/**
 * 格式化时间为相对时间描述
 * @param {string} timeStr - 格式为 "xxxx-yy-zz aa:bb" 的时间字符串
 * @returns {string} 格式化后的时间描述
 */
function formatTime(timeStr) {
  if (!timeStr) return '无效时间';

  // 解析输入时间
  const parseDate = (str) => {
    // 替换 '-' 为 '/' 以提高浏览器兼容性
    const dateStr = str.replace(/-/g, '/');
    // 处理没有时间部分的情况
    return dateStr.includes(':') ? new Date(dateStr) : new Date(dateStr + ' 00:00');
  };

  try {
    const inputDate = parseDate(timeStr);
    const now = new Date();

    // 验证日期有效性
    if (isNaN(inputDate.getTime())) return '无效时间';
    if (inputDate > now) return '未来时间';

    // 计算时间差（毫秒）
    const diff = now - inputDate;
    const diffSeconds = Math.floor(diff / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);

    // 获取输入时间的各个部分
    const formatTwoDigits = (num) => num.toString().padStart(2, '0');
    const inputYear = inputDate.getFullYear();
    const inputMonth = formatTwoDigits(inputDate.getMonth() + 1);
    const inputDay = formatTwoDigits(inputDate.getDate());
    const inputHours = formatTwoDigits(inputDate.getHours());
    const inputMinutes = formatTwoDigits(inputDate.getMinutes());

    // 判断并返回相应格式
    if (diffSeconds < 60) {
      return '刚刚';
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24 && isSameDay(inputDate, now)) {
      return `${diffHours}小时前`;
    } else if (isYesterday(inputDate, now)) {
      return `昨天 ${inputHours}:${inputMinutes}`;
    } else if (isDayBeforeYesterday(inputDate, now)) {
      return `前天 ${inputHours}:${inputMinutes}`;
    } else if (inputYear === now.getFullYear()) {
      return `${inputMonth}-${inputDay}`;
    } else {
      return `${inputYear}-${inputMonth}-${inputDay}`;
    }
  } catch (e) {
    console.error('时间格式化错误:', e);
    return '无效时间';
  }
}

// 辅助函数：判断是否为同一天
function isSameDay(date1, date2) {
  return date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate();
}

// 辅助函数：判断是否为昨天
function isYesterday(date, now) {
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  return isSameDay(date, yesterday);
}

// 辅助函数：判断是否为前天
function isDayBeforeYesterday(date, now) {
  const dayBeforeYesterday = new Date(now);
  dayBeforeYesterday.setDate(dayBeforeYesterday.getDate() - 2);
  return isSameDay(date, dayBeforeYesterday);
}

export default formatTime;
